import { List, Modal as AntModal, Space } from 'antd';
import { forwardRef, useRef, useState } from 'react';
import { Layout, registerComponent, iup } from '../../../../util';
import { AttachmentProvider, AttachmentProviderProps, useAttachment } from '../../AttachmentContext';
import { AttachmentButton, FileView, LabelSelect, RemarkModal } from '../../components';
import { ITableAttachmentProps } from '../../interface';
import { AttachmentToolbar, ImageUpload } from './components';
import './index.less';
const OriginFormAttachment = (
  props: Pick<
    ITableAttachmentProps,
    'tableStyle' | 'style' | 'thumbEnabled' | 'uploadRef' | 'labelConfig' | 'simpleUpload'
  >
) => {
  const [modal, contextHolder] = AntModal.useModal();
  const attachmentContextValues = useAttachment();
  const {
    beforeUploadValidate,
    accept,
    maxCount,
    disabled,
    actions,
    permission,
    attachmentRecordList,
    loading,
    isReady,
    uploading,
    onUploadStateChange,
    attachmentFileList,
    onContentChanged
  } = attachmentContextValues;
  const {
    style = {},
    thumbEnabled = false,
    uploadRef = useRef(null),
    tableStyle = {},
    labelConfig,
    simpleUpload = false
  } = props;
  const commonProps = {
    accept,
    maxCount,
    uploadRef,
    onUploaded: onContentChanged,
    onBeforeUpload: beforeUploadValidate,
    onUploadStateChange
  };
  const [curRow, setCurRow] = useState<object>();

  const content = thumbEnabled ? (
    <ImageUpload
      {...commonProps}
      attachmentFileList={attachmentFileList}
      disabled={!isReady || disabled || permission?.add === 0 || uploading}
      onRemove={(file) => {
        const params = [file] as unknown as typeof attachmentFileList;
        actions.delete(params);
      }}
    />
  ) : (
    <>
      <AttachmentToolbar
        {...commonProps}
        disabled={disabled}
        permission={permission}
        isReady={isReady}
        simpleUpload={simpleUpload}
        uploading={uploading}
        count={attachmentRecordList.length || 0}
        zipDownload={actions.zipDownload}
        openAttachment={() => actions.openTableAttachment({ labelConfig, modal })}
      />
      {attachmentFileList.length > 0 && (
        <Layout.Flex style={{ paddingTop: 12 }}>
          <List
            size="small"
            style={{
              ...tableStyle,
              maxHeight: 250,
              overflow: 'auto'
            }}
            dataSource={attachmentFileList}
            loading={loading}
            itemLayout="horizontal"
            renderItem={(row: any) => {
              const uploaded = row.status === 'done' || row.status === undefined;
              const listItemActions = [
                <a
                  style={{
                    color: 'var(--primary-color)',
                    visibility: uploaded ? 'unset' : 'hidden'
                  }}
                  onClick={() => {
                    if (!uploaded) return;
                    setCurRow(row);
                  }}
                >
                  备注
                </a>
              ];
              const isPreview = uploaded && actions.isPreview(row.asrName || row.fileName);
              const isFail = row.status === 'fail';
              return (
                <List.Item style={{ padding: '8px 4px' }} actions={listItemActions}>
                  <div className={`attachment-flex-center ${isFail ? 'upload-failed' : ''}`}>
                    <FileView
                      data={{
                        fileName: row.asrName || row.fileName,
                        fileSize: row.originFileSize || row.fileSize,
                        status: row.status,
                        percent: row.percent
                      }}
                      isPreview={isPreview}
                      handlePreview={() => row.asrFid && actions.preview(row.asrFid)}
                    />
                    <Space size={0} className="attachment-space-btn">
                      {uploaded && (
                        <>
                          <AttachmentButton
                            size="small"
                            type="link"
                            permissionStatus={permission?.preview}
                            disabled={!isPreview}
                            onClick={() => row.asrFid && actions.preview(row.asrFid)}
                          >
                            预览
                          </AttachmentButton>
                          <AttachmentButton
                            size="small"
                            type="link"
                            permissionStatus={permission?.download}
                            onClick={() => actions.download(row)}
                          >
                            下载
                          </AttachmentButton>
                        </>
                      )}
                      <AttachmentButton
                        size="small"
                        type="link"
                        disabled={disabled}
                        permissionStatus={permission?.delete}
                        onClick={() => actions.delete([row])}
                      >
                        删除
                      </AttachmentButton>
                    </Space>
                  </div>
                  <>
                    <div style={{ width: 150 }}>{row.asrFilldt}</div>
                    <div style={{ width: 70 }}>{row.userName}</div>
                    {!iup.isNullOrEmpty(labelConfig) && (
                      <LabelSelect
                        labelConfig={{
                          ...labelConfig,
                          value: row.label,
                          disabled: disabled || !uploaded
                        }}
                        fileId={row.asrFid}
                        onChangeCallback={onContentChanged}
                      />
                    )}
                  </>
                </List.Item>
              );
            }}
          />
        </Layout.Flex>
      )}
    </>
  );
  return (
    <Layout className="iup-form-attachment" style={style} direction="row">
      <Layout.Flex className="iup-form-attachment-content">
        {content}
        {contextHolder}
      </Layout.Flex>
      <RemarkModal
        data={curRow || {}}
        visible={curRow !== undefined}
        disabled={disabled}
        onCancel={() => setCurRow(undefined)}
        onSaved={onContentChanged}
      />
    </Layout>
  );
};

export const FormAttachment = forwardRef(
  (
    {
      style,
      thumbEnabled,
      uploadRef,
      tableStyle,
      simpleUpload,
      labelConfig,
      ...rest
    }: Omit<AttachmentProviderProps, 'children'>,
    ref
  ) => {
    return (
      <AttachmentProvider {...rest} ref={ref}>
        <OriginFormAttachment
          style={style}
          thumbEnabled={thumbEnabled}
          uploadRef={uploadRef}
          tableStyle={tableStyle}
          simpleUpload={simpleUpload}
          labelConfig={labelConfig}
        />
      </AttachmentProvider>
    );
  }
);
registerComponent({ Attachment: FormAttachment });
